import 'package:bruno/bruno.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_svg/svg.dart';
import 'package:images_picker/images_picker.dart';
import 'package:meal/constant/assets.dart';
import 'package:meal/constant/fonts.dart';
import 'package:meal/constant/sizes.dart';
import 'package:meal/ui/custom_tabbar.dart';
import 'package:meal/ui/my_upload.dart';
import 'package:meal/utils/colors.dart';
import 'package:meal/utils/styles.dart';

typedef DateValueCallback = void Function(DateTime dateTime, List<int> selectedIndex);

typedef DateVoidCallback = void Function();

typedef DateRangeValueCallback = Function(DateTime startDateTime, DateTime endDateTime,
    List<int> startSelectedIndex, List<int> endSelectedIndex);

class ToolsUtils {
  ToolsUtils._();

  static TextEditingController editingController(String content) {
    TextEditingController textEditingController = TextEditingController();
    textEditingController.text = content;
    textEditingController.value = TextEditingValue(
        text: content,
        selection: TextSelection.fromPosition(
            TextPosition(affinity: TextAffinity.downstream, offset: content.length)));
    return textEditingController;
  }

  static Image getAssetImageIcon(String assetName,
      {BoxFit? fit, double? width, double? height, double? scale}) {
    return Image.asset(
      '${Assets.iconUrl}/$assetName',
      fit: fit,
      width: width,
      height: height,
      scale: scale,
    );
  }

  static SvgPicture getAssetImageSvg(
    String assetName, {
    BoxFit fit = BoxFit.cover,
    double? width,
    double? height,
  }) {
    if (!assetName.endsWith('.svg')) {
      assetName = '$assetName.svg';
    }
    return SvgPicture.asset(
      '${Assets.svgUrl}/$assetName',
      width: width,
      height: height,
      fit: fit,
    );
  }

  static SvgPicture getUrlSvg(String url,
      {double? width, double? height, BoxFit fit = BoxFit.contain}) {
    return SvgPicture.network(url, width: width, height: height, fit: fit);
  }

  static AssetImage assetImageIcon(String assetName) {
    return AssetImage('${Assets.iconUrl}/$assetName');
  }

  static Image getAssetImage(
    String assetName, {
    BoxFit? fit,
    double? width,
    double? height,
  }) {
    return Image.asset(
      '${Assets.imgUrl}/$assetName',
      fit: fit,
      width: width,
      height: height,
    );
  }

  static AssetImage assetImage(String assetName) {
    return AssetImage(
      '${Assets.imgUrl}/$assetName',
    );
  }

  static Image getUrlImg(String url, {double? width, double? height}) {
    return Image.network(
      url,
      width: width,
      height: height,
    );
  }

  static ClientTabBar getClientTabBar(List<String> tabs, TabController controller,
      {Color backgroundColor = Colors.transparent, ValueChanged<int>? onTap}) {
    return ClientTabBar(
      tabs: tabs.map((e) {
        return Tab(
          text: e,
        );
      }).toList(),
      controller: controller,
      indicatorSize: TabBarIndicatorSize.label,
      isScrollable: true,
      padding: EdgeInsets.zero,
      indicator: RRecTabIndicator(
          radius: 1,
          insets: const EdgeInsets.only(bottom: 5),
          color: ColorsUtils.rgba(255, 110, 83, 1)),
      indicatorMinWidth: 36,
      indicatorWeight: 2,
      labelColor: ColorsUtils.parseColorFromHexString(ColorsUtils.colorFf6),
      labelStyle: StylesUtils.customTextStyle(color: ColorsUtils.colorFf6),
      unselectedLabelColor: ColorsUtils.parseColorFromHexString(ColorsUtils.color515),
      unselectedLabelStyle: StylesUtils.customTextStyle(color: ColorsUtils.color515),
      backgroundColor: backgroundColor,
      onTap: onTap,
    );
  }

  static BrnAppBar getDefaultBrnAppBar(String title,
      {dynamic actions, PreferredSizeWidget? bottom}) {
    return BrnAppBar(
      backgroundColor: ColorsUtils.rgba(255, 110, 83, 1),
      title: Text(title, style: StylesUtils.customTextStyle(fontSize: Sizes.default18)),
      elevation: 0,
      titleAlignment: Alignment.center,
      themeData: BrnAppBarConfig(
        iconSize: Sizes.default20,
        actionsStyle: BrnTextStyle(
            color: Colors.white, fontWeight: FontWeight.normal, fontSize: Sizes.default16),
        leadIconBuilder: () {
          return getAssetImageIcon('back.png');
        },
        leftAndRightPadding: Sizes.default10,
        titlePadding: EdgeInsets.zero,
      ),
      bottom: bottom,
      actions: actions,
    );
  }

  static BrnTextAction actions(String title, {VoidCallback? pressed}) {
    return BrnTextAction(
      title,
      iconPressed: pressed,
      themeData: BrnAppBarConfig(
          actionsStyle: BrnTextStyle(
              color: Colors.white, fontSize: Sizes.default16, fontWeight: FontWeight.normal)),
    );
  }

  static BrnAppBar customBrnAppBar(Widget title, {dynamic actions, PreferredSizeWidget? bottom}) {
    return BrnAppBar(
      backgroundColor: ColorsUtils.rgba(255, 110, 83, 1),
      title: title,
      elevation: 0,
      titleAlignment: Alignment.center,
      themeData: BrnAppBarConfig(
        iconSize: Sizes.default20,
        actionsStyle: BrnTextStyle(color: Colors.white),
        leadIconBuilder: () {
          return getAssetImageIcon('back.png');
        },
        leftAndRightPadding: Sizes.default10,
        titlePadding: EdgeInsets.zero,
      ),
      bottom: bottom,
      actions: actions,
    );
  }

  static Color getDefaultBackgroundColor() {
    return ColorsUtils.rgba(245, 245, 245);
  }

  static void openGalleryOrCamera(
      BuildContext context, SelectedImage? gallery, SelectedImage? camera,
      [int count = 10]) {
    showModalBottomSheet(
        context: context,
        backgroundColor: Colors.transparent,
        builder: (BuildContext context) {
          return BrnCommonActionSheet(
            title: '选择照片或者拍照',
            cancelTitle: '取消',
            actions: [
              BrnCommonActionSheetItem('打开相册，选取照片',
                  titleStyle: StylesUtils.customTextStyle(color: ColorsUtils.color333)),
              BrnCommonActionSheetItem('打开相机拍照',
                  titleStyle: StylesUtils.customTextStyle(color: ColorsUtils.color333)),
            ],
            clickCallBack: (int index, BrnCommonActionSheetItem item) {
              if (index == 0) {
                openGalleryImage(gallery, count);
              } else if (index == 1) {
                openCameraImage(camera);
              }
            },
          );
        });
  }

  static void openGalleryImage(SelectedImage? gallery, [int count = 10]) async {
    List<Media>? res = await ImagesPicker.pick(
        count: count, quality: 1.0, pickType: PickType.image, language: Language.Chinese);
    if (res != null && res.isNotEmpty) {
      gallery!(res);
    }
  }

  static void openCameraImage(SelectedImage? camera) async {
    List<Media>? res = await ImagesPicker.openCamera(quality: 1.0, language: Language.Chinese);
    if (res != null && res.isNotEmpty) {
      camera!(res);
    }
  }

  static Future<void> openCupertinoModalPopup(
      BuildContext context, SelectedImage gallery, SelectedImage camera) async {
    final cupertinoTheme = CupertinoTheme(
        data: const CupertinoThemeData(barBackgroundColor: Colors.white),
        child: CupertinoActionSheet(
          actions: [
            Container(
              color: Colors.white,
              child: CupertinoActionSheetAction(
                onPressed: () {
                  Navigator.pop(context, 1);
                },
                child: Text('拍照',
                    style: StylesUtils.customTextStyle(
                        fontSize: Sizes.default18, fontWeight: FontWeight.bold, color: '#409eff')),
              ),
            ),
            Container(
              color: Colors.white,
              child: CupertinoActionSheetAction(
                onPressed: () {
                  Navigator.pop(context, 2);
                },
                child: Text(
                  '手机相册选取',
                  style: StylesUtils.customTextStyle(
                      fontSize: Sizes.default18, fontWeight: FontWeight.bold, color: '#409eff'),
                ),
              ),
            )
          ],
          cancelButton: CupertinoActionSheetAction(
            isDestructiveAction: true,
            onPressed: () {
              Navigator.pop(context, 0);
            },
            child: Text(
              '取消',
              style: StylesUtils.customTextStyle(
                  fontSize: Sizes.default20, fontWeight: FontWeight.bold, color: '#409eff'),
            ),
          ),
        ));
    int? result = await showCupertinoModalPopup<int>(
        context: context,
        barrierColor: Colors.black54,
        semanticsDismissible: true,
        builder: (BuildContext context) => cupertinoTheme);
    if (result == 1) {
      /// 相机
      openCameraImage((List<Media> res) {
        gallery.call(res);
      });
    } else if (result == 2) {
      /// 相册
      openGalleryImage((List<Media> res) {
        camera.call(res);
      }, 1);
    }
  }

  static void openDataPicker(BuildContext context, List<BrnMultiDataPickerEntity> data,
      ConfirmButtonClick confirmButtonClick,
      {String title = '请选择'}) {
    BrnMultiDataPicker(
      context: context,
      delegate: BrnDefaultMultiDataPickerDelegate(data: data),
      confirmClick: confirmButtonClick,
      title: title,
      titleTextStyle: StylesUtils.customTextStyle(
          color: ColorsUtils.color333, fontSize: Sizes.default16, fontWeight: Fonts.w6),
      cancelTextStyle:
          StylesUtils.customTextStyle(color: ColorsUtils.color333, fontSize: Sizes.default16),
      confirmTextStyle:
          StylesUtils.customTextStyle(color: ColorsUtils.colorFf6, fontSize: Sizes.default16),
      themeData: BrnPickerConfig(
          cornerRadius: Sizes.default15,
          titleHeight: Sizes.default50,
          dividerColor: ColorsUtils.parseColorFromHexString('#D7D7D7'),
          itemHeight: Sizes.default40,
          itemTextSelectedStyle: BrnTextStyle(
              fontWeight: FontWeight.w700,
              color: ColorsUtils.parseColorFromHexString(ColorsUtils.color333),
              fontSize: Sizes.default15),
          itemTextStyle: BrnTextStyle(
              color: ColorsUtils.parseColorFromHexString(ColorsUtils.color797),
              fontWeight: FontWeight.normal,
              fontSize: Sizes.default14)),
    ).show();
  }

  static void openDatePicker(
    BuildContext context, {
    String format = 'yyyy-MM-dd',
    DateTime? max,
    DateTime? min,
    BrnDateTimePickerMode pickerMode = BrnDateTimePickerMode.date,
    DateValueCallback? onConfirm,
    DateVoidCallback? onClose,
    DateValueCallback? onChange,
    DateVoidCallback? onCancel,
  }) {
    BrnDatePicker.showDatePicker(
      context,
      maxDateTime: max,
      minDateTime: min,
      initialDateTime: DateTime.now(),
      pickerMode: pickerMode,
      minuteDivider: 30,
      pickerTitleConfig: BrnPickerTitleConfig.Default,
      dateFormat: format,
      onConfirm: onConfirm,
      onClose: onClose,
      onCancel: onCancel,
      onChange: onChange,
      themeData: BrnPickerConfig(
          cornerRadius: Sizes.default15,
          titleHeight: Sizes.default50,
          itemHeight: Sizes.default40,
          dividerColor: ColorsUtils.parseColorFromHexString('#D7D7D7'),
          itemTextSelectedStyle: BrnTextStyle(
              fontWeight: FontWeight.w700,
              color: ColorsUtils.parseColorFromHexString(ColorsUtils.color333),
              fontSize: Sizes.default15),
          itemTextStyle: BrnTextStyle(
              color: ColorsUtils.parseColorFromHexString(ColorsUtils.color797),
              fontWeight: FontWeight.normal,
              fontSize: Sizes.default14)),
    );
  }

  static void openDateRangePicker(
    BuildContext context, {
    String format = 'yyyy-MM-dd',
    DateTime? max,
    DateTime? min,
    BrnDateTimeRangePickerMode pickerMode = BrnDateTimeRangePickerMode.date,
    DateVoidCallback? onCancel,
    DateVoidCallback? onClose,
    DateRangeValueCallback? onChange,
    DateRangeValueCallback? onConfirm,
  }) {
    BrnDateRangePicker.showDatePicker(
      context,
      maxDateTime: max,
      minDateTime: min,
      initialStartDateTime: DateTime.now(),
      pickerMode: pickerMode,
      minuteDivider: 30,
      pickerTitleConfig: BrnPickerTitleConfig.Default,
      dateFormat: format,
      onConfirm: onConfirm,
      onClose: onClose,
      onCancel: onCancel,
      onChange: onChange,
      themeData: BrnPickerConfig(
          cornerRadius: Sizes.default15,
          titleHeight: Sizes.default50,
          itemHeight: Sizes.default40,
          dividerColor: ColorsUtils.parseColorFromHexString('#D7D7D7'),
          itemTextSelectedStyle: BrnTextStyle(
              fontWeight: FontWeight.w700,
              color: ColorsUtils.parseColorFromHexString(ColorsUtils.color333),
              fontSize: Sizes.default15),
          itemTextStyle: BrnTextStyle(
              color: ColorsUtils.parseColorFromHexString(ColorsUtils.color797),
              fontWeight: FontWeight.normal,
              fontSize: Sizes.default14)),
    );
  }

  static Image iconRightArrow([double width = 16, double height = 16]) {
    return BrunoTools.getAssetSizeImage(BrnAsset.iconRightArrow, width, height);
  }
}
